<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="js/ol.css">
    <script src="js/ol-debug.js"></script>
    <script src="lib/jquery/jquery-3.3.1.min.js"></script>
    <script src="lib/bootstrap/js/bootstrap.js"></script>
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.css">
    <style>
        .pop {
            width: 70px;
            height: 20px;
            /*            border: 1px solid #088;
                        border-radius: 10px;*/
            background-color: #0FF;
            opacity: 0.7;
        }
    </style>
</head>
<body>
<div class="pop" style="display: none;">123</div>
<div id="map" style="width: 100%">
    <div style="position: absolute;left: 100px; z-index: 10">
        <button id="bt_add"  >添加</button>
        <button id="bt_delete"  >删除</button>
        <div style="display: inline-block;border: 1px solid #b92c28;margin-left: 30px">
            <button id="bt_modify" >修改</button>
            <button id="bt_save" >保存</button>

        </div>
    </div>
</div>
<script>
    var webip="http://localhost:";
    var gisip="http://localhost:";
    var webport="8080/";
    var gisport="8080/";
    /*********************************************************地图初始化**********************************************************/
    /*底图初始化*/
    var format = 'image/png';
    //view
    var view=new ol.View({
        // 设置成都为地图中心
        center: ol.proj.transform([508881,299705],"EPSG:3857","EPSG:3857"),
        zoom: 18
    });
    //var osm=new ol.layer.Tile({source: new ol.source.OSM()});


    var tilePoint = new ol.layer.Tile({
        //visible: false,
        source: new ol.source.TileWMS({
            url: 'http://localhost:8080/geoserver/whuxcy/wms',
            params: {'FORMAT': format,
                'VERSION': '1.1.1',
                tiled: true,
                "STYLES": '',
                "LAYERS": 'whuxcy:point'
                //"exceptions": 'application/vnd.ogc.se_inimage',
                //tilesOrigin: 8176078.237520734 + "," + 704818.0275364731
            }
        })
    });
    var tilePolyline = new ol.layer.Tile({
        //visible: false,
        source: new ol.source.TileWMS({
            url: 'http://localhost:8080/geoserver/whuxcy/wms',
            params: {'FORMAT': format,
                'VERSION': '1.1.1',
                tiled: true,
                "STYLES": '',
                "LAYERS": 'whuxcy:polyline'
                //"exceptions": 'application/vnd.ogc.se_inimage',
                //tilesOrigin: 8176078.237520734 + "," + 704818.0275364731
            }
        })
    });
    var tilePolygon = new ol.layer.Tile({
        //visible: false,
        source: new ol.source.TileWMS({
            url: 'http://localhost:8080/geoserver/whuxcy/wms',
            params: {'FORMAT': format,
                'VERSION': '1.1.1',
                tiled: true,
                "STYLES": '',
                "LAYERS": 'whuxcy:polygon'
                //"exceptions": 'application/vnd.ogc.se_inimage',
                //tilesOrigin: 8176078.237520734 + "," + 704818.0275364731
            }
        })
    });
    /*矢量图层初始化*/
    /////////////////////////////////////
    var polygonTypename="xcy:polygon";
    var polygonVectorSource = new ol.source.Vector({
        features:[]
    });
/*    var polygonVectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: function(extent) {
            return gisip+gisport+'geoserver/xcy/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName='+polygonTypename+'&outputFormat=application%2Fjson';
        },
        strategy: ol.loadingstrategy.bbox
    });*/
    var polygonVectorLayer = new ol.layer.Vector({
        title:"面",
        source: polygonVectorSource,
        style: styleFunction,
        renderMode:'image'
    });

    setTimeout(showHeight,2000);
    function showHeight() {
        $.ajax({
            type: "GET",
            url: gisip+gisport+'geoserver/xcy/wfs?service=WFS&request=GetFeature&typeName='+polygonTypename+'&outputFormat=application%2Fjson',
            dataType:'json',
            success: function(data){
                var features=data.features;
                for(var i=0;i<features.length;i++)
                {
                    var feature=features[i];
                    var ft=new ol.Feature({
                        geometry:new ol.geom.MultiPolygon(feature.geometry.coordinates),
                        //attr:feature
                    });
                    ft.setId(feature.id);
                    ft.attr=feature;
                    var geometry=ft.getGeometry();
                    polygonVectorSource.addFeature(ft);
/*                    var dom=$("<span/>").addClass("pop").html(feature.properties.Text);
                    var overlay= new ol.Overlay({
                        element:dom[0],
                        //element:$(".pop")[0],
                        position:feature.geometry.coordinates,
                        //positioning:"top-left"
                    });
                    map.addOverlay(overlay);*/
                }
            }

        });
    }
    var fill = new ol.style.Fill({
        color: '#dd942e'
    });
    var stroke = new ol.style.Stroke({
        color: '#cc1000',
        width: 1.25
    });
    function styleFunction(feature) {

        return new ol.style.Style({
            fill:fill,
            stroke:stroke,
            image:new ol.style.Circle({
                radius: 5,
                fill: new ol.style.Fill({
                    color: "#389BCD",
                    opacity: 0.5
                })
            })
        });
    }
    // map
    var map = new ol.Map({
        layers: [
            //tilePoint,
            tilePolyline,
            //tilePolygon,
            polygonVectorLayer
        ],
        view:view,
        target: 'map',
        renderer:"canvas"
    });
    function  st(feature,isSelect) {
        return  new ol.style.Style({
            fill: fill,
            stroke: new ol.style.Stroke({
                color: '#319FD3',
                width: 1
            }),
            image:new ol.style.RegularShape({
                fill: fill,
                stroke: stroke,
                points: 3,
                radius: 10,
                //rotation: Math.PI / 4,
                angle: 0
            })
        });
    }
    /*点击事件初始化*/
    //选中交互-删除
    var select=new ol.interaction.Select({
        //condition: ol.events.condition.pointerMove,
        layers:[polygonVectorLayer],
        multi:true,
        style:function (feature) {
            return st(feature,true);
        }
    });
    select.on('select', function (evt) {
        var feature = evt.selected[0];

        /*            var newFeature = new ol.Feature({
         the_geom: new ol.geom.MultiPolygon([feature.getGeometry().getCoordinates()]),
         Layer:"Layer",
         SubClasses:"SubClasses",
         ExtendedEn:"ExtendedEn",
         Linetype:"Linetype",
         EntityHand:"EntityHand",
         Text:"Text"
         });*/
        //feature.set('id_',feature.attr.id);
        var format = new ol.format.WFS();
        var xml = format.writeTransaction(null, null, [feature], {
            featureNS: 'http://geoserver.org/nyc',
            featurePrefix: "xcy",//工作空间名称
            featureType: "polygon"//图层名称
        });
        var serializer = new XMLSerializer();
        var featString = serializer.serializeToString(xml);

        $.ajax({
            url: "http://localhost:8080/geoserver/xcy/wfs",
            type: "POST",
            data: featString,
            contentType: 'text/xml',
            success: function (req) {
                console.log(req);
                //window.location.reload();
            }
        });
    });
    select.setActive(false);
    map.addInteraction(select);
    //选中交互-修改
    var modifySelect=new ol.interaction.Select({
        //condition: ol.events.condition.pointerMove,
        layers:[polygonVectorLayer],
        multi:true,
        style:function (feature) {
            return st(feature,true);
        }
    });
    modifySelect.setActive(false);
    map.addInteraction(modifySelect);
    /*添加要素添加*/
    var draw = new ol.interaction.Draw({
        source: polygonVectorSource,
        type: "Polygon",
        stopClick:true,
        freehand:false
    });
    map.addInteraction(draw);
    draw.setActive(false);
    /*添加要素编辑*/
    /*
     var modify = new ol.interaction.Modify({source: pointVectorSource});
     */
    var modify = new ol.interaction.Modify({
        features: modifySelect.getFeatures()//要修改的对象
    });
    modify.on("modifyend",function (evt) {
/*        var features=e.features.array_;
        var wktformat= new ol.format.WKT();
        alert(wktformat.writeGeometry(features[0].getGeometry()));*/
        modifyFeatures= evt.features;

    });
    modify.setActive(false);
    map.addInteraction(modify);
    var snap = new ol.interaction.Snap({source: polygonVectorSource});
    map.addInteraction(snap);
    var modifyFeatures=null;
    /*********************************************************控件初始化**********************************************************/
    //添加
    $("#bt_add").click(function (e) {
        if (select.getActive())
        {
            select.setActive(false);
        }
        if (modifySelect.getActive())
        {
            modifySelect.setActive(false);
        }
        draw.setActive(true);
        draw.once("drawend",function (e) {
            draw.setActive(false);
            //map.removeInteraction(draw);
            var feature=e.feature;
            /*        var wktformat= new ol.format.WKT();
             alert(wktformat.writeGeometry(feature.getGeometry()));*/
            var newFeature = new ol.Feature({
                the_geom: new ol.geom.MultiPolygon([feature.getGeometry().getCoordinates()]),
                Layer:"Layer",
                SubClasses:"SubClasses",
                ExtendedEn:"ExtendedEn",
                Linetype:"Linetype",
                EntityHand:"EntityHand",
                Text:"Text"
            });
            //newFeature.setGeometryName("geometry");
            var WFSTSerializer = new ol.format.WFS();
            var featObject = WFSTSerializer.writeTransaction([newFeature],
                null, null, {
                    featureNS: 'http://geoserver.org/nyc',
                    featurePrefix: "xcy",//工作空间名称
                    featureType: "polygon",//图层名称
                    //srsName: 'EPSG:4326'
                });
            var serializer = new XMLSerializer();
            var featString = serializer.serializeToString(featObject);
            $.ajax({
                url: "http://localhost:8080/geoserver/wfs",
                type:"POST",
                data: featString,
                contentType: 'text/xml',
                success: function (req) {
                    console.log(req);
                    //window.location.reload();
                }
            });

        });
    });
    //删除
    $("#bt_delete").click(function (e) {
        if (!select.getActive())
        {
            select.setActive(true);
        }
        if (modifySelect.getActive())
        {
            modifySelect.setActive(false);
        }
    });
    //修改
    $("#bt_modify").click(function (e) {
        if (select.getActive())
        {
            select.setActive(false);
        }
        if (!modifySelect.getActive())
        {
            modifySelect.setActive(true);
        }
        if (!modify.getActive())
        {
            modify.setActive(true);
        }

    });
    //保存
    $("#bt_save").click(function (e) {
        if (modifyFeatures && modifyFeatures.getLength() > 0) {

            var modifyFeature = modifyFeatures.item(0).clone();
            modifyFeature.setId(modifyFeatures.item(0).getId());

            modifyFeature.set('Text', '修改后的text');
/*            modifyFeature.set('the_geom', modifyFeature.getGeometry());
            modifyFeature.unset("geometry");*/
            modifyFeature.setGeometryName("the_geom");
            var format = new ol.format.WFS();
            var xml = format.writeTransaction(null, [modifyFeature], null, {
                featureNS: 'http://geoserver.org/nyc',
                featurePrefix: "xcy",//工作空间名称
                featureType: "polygon"//图层名称
            });

            var serializer = new XMLSerializer();
            var featString = serializer.serializeToString(xml);

            $.ajax({
                url: "http://localhost:8080/geoserver/wfs",
                type: "POST",
                data: featString,
                contentType: 'text/xml',
                success: function (req) {
                    //select.getFeatures().clear();
                    console.log(req);

                }
            });
        }


    })



</script>
</body>
</html>